package cn.pet_know.common.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class ConverterUtils {

    // 转换对象并返回目标类型
    public static <T> T copyR(Object source,T target) {
        BeanUtils.copyProperties(source,target);
        return target;
    }

    // 转换List中的对象元素,并返回结果
    public static <T> List<T> listCopyR(List<? extends Object> source, Class<T> target) {
        ArrayList<T> objects = new ArrayList<>();
        for (Object o : source) {
            try {
                objects.add(copyR(o,target.newInstance()));
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }

        }
        return objects;
    }

    // 转换分页
    public static <T> Page<T> pageCopyR(Page<? extends Object> source, Class<T> target) {
        List<T> ts = listCopyR(source.getRecords(), target);
        Page<T> tPage = new Page<>();
        Page<T> result = copyR(source, tPage);
        result.setRecords(ts);
        return result;
    }
}
